<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :inline="true" :model="queryParams" label-width="68px">
      <el-form-item label="单据类型" prop="stockType">
        <el-select v-model="queryParams.stockType" clearable placeholder="请选择单据类型" size="small">
          <el-option
            v-for="dict in typeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="单据标题" prop="stockTitle">
        <el-input
          v-model="queryParams.stockTitle"
          clearable
          placeholder="请输入单据标题"
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="单据状态" prop="stockState">
        <el-select v-model="queryParams.stockState" clearable placeholder="请选择单据状态" size="small">
          <el-option
            v-for="dict in stateOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="单据所属" prop="own">
        <el-select v-model="own" clearable placeholder="请选择" size="small" @change="ownChange">
          <el-option
            v-for="item in ownOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" size="mini" type="primary" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="stockList">
      <el-table-column align="center" type="selection" width="55"/>
      <el-table-column :formatter="codeFormat" align="center" label="单据编号" prop="stockId"/>
      <el-table-column :formatter="typeFormat" align="center" label="单据类型" prop="stockType"/>
      <el-table-column align="center" label="单据标题" prop="stockTitle"/>
      <el-table-column align="center" label="创建人" prop="createName"/>
      <el-table-column align="center" label="提交时间" prop="createTime" width="180"/>
      <el-table-column align="center" label="状态">
        <template slot-scope="scope">
          <div v-if="scope.row.stockState != 0">
            {{ stateFormat(scope.row) }}
          </div>
          <div v-else>
            {{ scope.row.taskName }}
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['activiti:stock:query']"
            icon="el-icon-document"
            size="mini"
            type="text"
            @click="historyFory(scope.row)"
          >单据详情
          </el-button>
          <el-button v-if="'0' === scope.row.stockState"
                     v-hasPermi="['activiti:stock:query']"
                     icon="el-icon-finished"
                     size="mini"
                     type="text"
                     @click="checkTheSchedule(scope.row)"
          >查看进度
          </el-button>
          <el-button v-if="'0' === scope.row.stockState && own === 1"
                     v-hasPermi="['activiti:stock:edit']"
                     icon="el-icon-edit"
                     size="mini"
                     type="text"
                     @click="revokeStock(scope.row)"
          >撤销
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :limit.sync="queryParams.pageSize"
      :page.sync="queryParams.pageNum"
      :total="total"
      @pagination="getList"
    />

    <el-dialog :visible.sync="modelVisible" append-to-body title="进度查询" width="1680px">
      <div style="position:relative;height: 100%;">
        <iframe id="iframe" :src="modelerUrl" frameborder="0" height="720px" scrolling="auto" width="100%"/>
      </div>
    </el-dialog>

    <!-- 查看详细信息话框 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body width="1680px">
      <stock-detail ref="stockDetail" :stock-id="selectStock.stockId"/>
      <div v-for="(item, index) in form" :key="index">
        <div class="orderTitle">{{ item.taskNodeName }}</div>
        <el-form ref="form" :disabled="true" :inline="true" :model="item" label-width="80px" size="mini">
          <el-form-item label="审批人" prop="createBy">
            <el-input v-model="item.createBy"/>
          </el-form-item>
          <el-form-item label="审批时间" prop="createTime">
            <el-input v-model="item.createTime"/>
          </el-form-item>
        </el-form>
        <div
          v-for="(domain, index) in item.formJson"
          :key="index"
          :label="domain.controlLable"
        >
          <parser ref="formCustom" :form-conf="domain.json"/>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="printStock">打 印</el-button>
        <el-button @click="open = !open">关闭</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listAllStock, listStock, revoke } from '@/api/activiti/stock'
import { getDefinitionsByInstanceId } from '@/api/activiti/definition'
import { historyFormData } from '@/api/activiti/historyFormdata'
import StockDetail from '@/views/activiti/stock/StockDetail'
import Parser from 'form-gen-parser'
import { formJsonShow } from '@/api/tool/form'

export default {
  name: 'StockHistory',
  components: {
    StockDetail,
    Parser
  },
  data() {
    return {
      modelVisible: false,
      modelerUrl: '',
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 是否显示弹出层
      open: false,
      // 弹出层标题
      title: '',
      // 请假表格数据
      stockList: [],
      // 动态表单内容
      form: [],
      // 选中的单据id
      selectStock: {},
      // 单据类型字典
      typeOptions: [],
      // 单据状态字典
      stateOptions: [],
      // 单据所属
      own: 1,
      ownOptions: [
        {
          value: 1,
          label: '我的'
        },
        {
          value: 2,
          label: '本部门'
        }
      ],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderByColumn: 'createTime',
        isAsc: 'DESC',
        stockType: null,
        stockTitle: null,
        instanceId: null,
        stockState: null,
        createBy: null
      }
    }
  },
  created() {
    this.getList()
    this.getDicts('activiti_stock_type').then(response => {
      this.typeOptions = response.data
    })
    this.getDicts('activiti_flow_type').then(response => {
      this.stateOptions = response.data
    })
  },
  methods: {
    // 撤销
    revokeStock(row) {
      this.$confirm('是否确认撤销 ' + row.stockTitle + '?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return revoke(row.stockId)
      }).then(response => {
        this.$message.success('撤销成功')
        this.getList()
      })
    },
    ownChange(val) {
      this.own = val
      this.getList()
    },
    // 查询我的出入库单据列表
    getList() {
      this.loading = true
      if (this.own === 1) {
        listStock(this.queryParams).then(response => {
          this.stockList = response.rows
          this.total = response.total
          this.loading = false
        })
      } else if (this.own === 2) {
        listAllStock(this.queryParams).then(response => {
          this.stockList = response.rows
          this.total = response.total
          this.loading = false
        })
      }
    },
    // 请假类型字典翻译
    typeFormat(row, column) {
      return this.selectDictLabel(this.typeOptions, row.stockType)
    },
    // 单据编号为单据ID最后一个分隔符后的字符串
    codeFormat(row, column) {
      let lastIndex = row.stockId.lastIndexOf('-')
      return row.stockId.substring(lastIndex + 1)
    },
    // 打印按钮点击事件
    printStock() {
      // 调用子组件的方法
      this.$refs.stockDetail.print()
    },
    // 状态字典翻译
    stateFormat(row, column) {
      return this.selectDictLabel(this.stateOptions, row.stockState)
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 审批详情 */
    historyFory(row) {
      this.open = true
      this.title = '审批详情'
      this.selectStock = row
      this.historyFromData(row.stockId)
    },
    // 审批 动态表单
    historyFromData(businessKey) {
      historyFormData(businessKey).then(response => {
        this.form = response.data
        this.form.forEach((item, index) => {
          this.showFormJson(item.formKey, index)
        })
      })
    },
    /** 进度查看 */
    checkTheSchedule(row) {
      this.modelVisible = true
      getDefinitionsByInstanceId(row.instanceId).then(response => {
        let data = response.data
        this.modelerUrl = '#/activiti/definition/edit?type=lookBpmn&instanceId=' + row.instanceId + '&deploymentFileUUID=' + data.deploymentId + '&deploymentName=' + encodeURI(data.resourceName)
        this.modelVisible = true
      })
    },
    // 渲染动态表单
    showFormJson(formKey, index) {
      if (!formKey || formKey === '') {
        return false
      }
      formJsonShow(formKey).then(response => {
        let formJson = []
        for (let oncekey in response.data) {
          let datas = response.data[oncekey]
          if (datas) {
            for (let i = 0; i < datas.length; i++) {
              let once = datas[i]
              if (/^{/.test(once)) {
                formJson.push({
                  json: JSON.parse(once)
                })
              }
            }
          }
        }
        this.$set(this.form[index], 'formJson', formJson)
        this.disableForm(this.form[index].formJson[0].json)
        if (this.form[index].formData != undefined) {
          this.fillFormData(this.form[index].formJson[0].json, JSON.parse(this.form[index].formData))
          this.$set(this.form[index], 'formJson', formJson)
        }
      })
    },
    // 动态表单值回写
    fillFormData(form, data) {
      form.fields.map(item => {
        if (item.__vModel__) {
          const val = data[item.__vModel__]
          if (val) {
            item.__config__.defaultValue = val
          }
          return item
        } else {
          if (item.__config__ && item.__config__.children && item.__config__.children.length > 0) {
            item.__config__.children.forEach(child => {
              const childVal = data[child.__vModel__]
              if (childVal) {
                child.__config__.defaultValue = childVal
              }
            })
            return item
          }
        }
      })
    },
    // 设置动态表单禁用状态
    disableForm(form) {
      form.fields.map(item => {
        if (item.__vModel__) {
          item.disabled = true
          return item
        } else {
          if (item.__config__ && item.__config__.children && item.__config__.children.length > 0) {
            item.__config__.children.forEach(child => {
              child.disabled = true
            })
            return item
          }
        }
      })
    }
  }
}
</script>

<style scoped>
.orderTitle {
  font-size: 16px;
  font-weight: 700;
  line-height: 1.5;
  margin-bottom: 7px;
  margin-top: 7px;
  color: rgba(0, 0, 0, 0.85)
}

.orderLabel {
  color: rgba(0, 0, 0, .85);
  font-weight: 400;
  font-size: 15px;
  line-height: 22px;
  padding-bottom: 7px;
  margin-right: 8px;
  white-space: nowrap;
  display: table-cell;
}

.orderContent {
  font-size: 14px;
  line-height: 1.5;
  width: 100%;
  padding-bottom: 7px;
  color: rgba(0, 0, 0, 0.65);
  display: table-cell;
}

.el-input /deep/ .el-input__inner {
  color: #888888 !important;
  cursor: pointer;
}
</style>
